package com.lihui.exercises;

import java.util.*;


/**
 * @Author 比特就业课
 * @Date 2022-11-17
 */
public class Exe_01 {
    public static void main(String[] args) {
        // 生成10万个元素的数组
        int capacity = 10_000;
        int[] array = new int[capacity];
        // 随机生成
        Random random = new Random();
        for (int i = 0; i < capacity; i++) {
            int value = random.nextInt(capacity);
            array[i] = value;
        }

        func3(array);

    }

    // 去除10万个数据中的重复数据
    public static void func1 (int[] array) {
        HashSet<Integer> set = new HashSet<>();
        for (int i = 0; i < array.length; i++) {
            set.add(array[i]);
        }
        System.out.println(set.size());
    }

    // 查找10万个数据中第一次重复的数据
    public static int func2 (int[] array) {
        HashSet<Integer> set = new HashSet<>();
        for (int i = 0; i < array.length; i++) {
            boolean input = set.add(array[i]);
            if(!input){
                return array[i];
            }
        }
        return -1;
    }

    // 统计10万个数据中，每个每个数据出现的次数
    public static void func3 (int[] array) {
        HashMap<Integer,Integer> hashMap = new HashMap<>();
        for (int i = 0; i < array.length; i++) {
            if (hashMap.containsKey(array[i])) {
                hashMap.put(array[i], hashMap.get(array[i]) + 1);
            }else {
                hashMap.put(array[i] ,1);
            }
        }
        //使用getOrDefault
//        for (int i = 0; i < array.length; i++) {
//            int count = hashMap.getOrDefault(array[i],0);
//            hashMap.put(array[i],count + 1);
//        }


    }
//前k 个 高频单词,用优先级队列实现
    public List<String> topKFrequent(String[] words, int k) {
        List<String> list = new ArrayList<>();
        if(words == null || words.length == 0 || k <= 0){
            return list;
        }

        //定义一个map来统计单词的个数
        Map<String,Integer> map = new HashMap<>();
        for(int i = 0; i < words.length; i++){
            int count = map.getOrDefault(words[i],0);
            map.put(words[i],count+1);
        }

        PriorityQueue<Map.Entry<String,Integer>> queue = new PriorityQueue<>(new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                if(o1.getValue() != o2.getValue()){
                    return o1.getKey().compareTo(o2.getKey());
                }
                return o2.getValue() - o1.getValue();
            }
        });

        for (Map.Entry<String,Integer> entry: map.entrySet()) {
            queue.offer(entry);
            if(queue.size() > k){
                queue.poll();
            }
        }
        while (!queue.isEmpty()){
            list.add(queue.poll().getKey());
        }
        Collections.reverse(list);
        return list;
    }
}
